package com.myapp.ruyixing.ui;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.myapp.ruyixing.R;
import com.myapp.ruyixing.http.RYHttpClient;
import com.myapp.ruyixing.http.RYHttpResponseHandler;
import com.myapp.ruyixing.model.NearbyStores;
import com.myapp.ruyixing.model.NearbyStores.Store;
import com.myapp.ruyixing.ui.widget.TitleBar;
import com.myapp.ruyixing.utils.BitmapLruCache;
import com.myapp.ruyixing.utils.LoginHelper;
import com.myapp.ruyixing.utils.UIUtils;

public class SigninFragment extends Fragment implements OnItemClickListener {

	private ListView mListView;
	private TextView mEmptyView;
	private TitleBar mTitleBar;
	private View mLoadingView;

	private RYHttpResponseHandler mHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			NearbyStores stores = (NearbyStores) o;

			if (stores != null && stores.items != null) {
				MyListAdapter adapter = new MyListAdapter(stores.items);
				mListView.setAdapter(adapter);
			}
			mListView.setEmptyView(mEmptyView);
			mTitleBar.showLoading(false);
			mLoadingView.setVisibility(View.GONE);
		}

		@Override
		public void onFailure(Throwable throwable) {
			if (getActivity() != null && !isDetached() && isVisible()) {
				Toast.makeText(getActivity(), "加载失败", Toast.LENGTH_SHORT)
						.show();
			}
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_signin, container, false);
	};

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		mListView = (ListView) view.findViewById(android.R.id.list);
		mEmptyView = (TextView) view.findViewById(android.R.id.empty);
		mTitleBar = (TitleBar) view.findViewById(R.id.title_bar);
		mLoadingView = view.findViewById(R.id.my_loading);

		mListView.setOnItemClickListener(this);

		final EditText search = (EditText) view.findViewById(R.id.edit_search);
		search.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				String s = search.getText().toString();
				s = s.trim();
				mLoadingView.setVisibility(View.VISIBLE);
				if (!TextUtils.isEmpty(s)) {
					RYHttpClient.getSearchSigninList(getActivity(), 0, 500,
							mHandler, s);
				} else {
					RYHttpClient.getSigninList(getActivity(), 0, 500, mHandler);
				}

				return false;
			}
		});
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		mTitleBar.showLoading(true);
		RYHttpClient.getSigninList(getActivity(), 0, 500, mHandler);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Store store = (Store) mListView.getAdapter().getItem(position);

		if (!LoginHelper.getInstance().ensureLogin(getActivity())) {
			return;
		}

		startActivity(new Intent(getActivity(),
				ShopAddRegistrationActivity.class).putExtra(
				ShopDetailActivity.INTENT_SHOP_ID, store.merchant_id).putExtra(
				ShopDetailActivity.INTENT_SHOP_NAME, store.merchant_name));
	}

	private class ViewHolder {
		TextView mTitleView;
		TextView mPriceView;
		NetworkImageView mShopImage;
		TextView mDistanceView;
		ImageView mScoreView;
		TextView mLabelsView;
		View mCardIndicatorView;
		View mTicketIndicatorView;
		View mBenifitIndicatorView;
	}

	private class MyListAdapter extends ArrayAdapter<Store> {

		private RequestQueue mQueue;
		private ImageLoader mImageLoader;

		public MyListAdapter(List<Store> list) {
			super(getActivity(), -1, list);
			mQueue = Volley.newRequestQueue(getActivity());
			mImageLoader = new ImageLoader(mQueue, new BitmapLruCache());
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(getActivity())
						.inflate(R.layout.shop_list_item, parent, false);

				ViewHolder holder = new ViewHolder();
				holder.mTitleView = (TextView) convertView
						.findViewById(R.id.text_shop_name);
				holder.mPriceView = (TextView) convertView
						.findViewById(R.id.text_average_cost);
				holder.mShopImage = (NetworkImageView) convertView
						.findViewById(R.id.image_shop);
				holder.mDistanceView = (TextView) convertView
						.findViewById(R.id.text_distance);
				holder.mScoreView = (ImageView) convertView
						.findViewById(R.id.score);
				holder.mLabelsView = (TextView) convertView
						.findViewById(R.id.text_keywords);
				holder.mCardIndicatorView = convertView
						.findViewById(R.id.img_ka);
				holder.mTicketIndicatorView = convertView
						.findViewById(R.id.img_quan);
				holder.mBenifitIndicatorView = convertView
						.findViewById(R.id.img_hui);
				
				convertView.setTag(holder);
			}

			ViewHolder mHolder = (ViewHolder) convertView.getTag();

			NearbyStores.Store item = getItem(position);

			mHolder.mTitleView.setText(item.merchant_name);
			int price = 0;
			try {
				price = Integer.parseInt(item.price);
			} catch (Exception e) {
			}
			mHolder.mPriceView.setText(getString(R.string.store_price, ""
					+ price));
			mHolder.mLabelsView.setText(item.keywords);
			mHolder.mScoreView.setImageLevel(item.score);
			long sDistance = item.distance;
			String picurl = item.picurl;

			if (sDistance >= 0) {
				String distance = "";
				if (sDistance >= 1000) {
					if (sDistance >= 1000000) {
						distance = "999+km";
					} else {
						distance = String.format("%.1fkm",
								((double) sDistance) / 1000);
					}
				} else {
					distance = sDistance + "m";
				}
				mHolder.mDistanceView.setText(distance);
			}

			if (!TextUtils.isEmpty(picurl)) {
				mHolder.mShopImage.setImageUrl(picurl, mImageLoader);
			}

			UIUtils.setViewVisibility(mHolder.mCardIndicatorView,
					"1".equals(item.card));
			UIUtils.setViewVisibility(mHolder.mTicketIndicatorView,
					"1".equals(item.ticket));
			UIUtils.setViewVisibility(mHolder.mBenifitIndicatorView,
					"1".equals(item.benefit));

			return convertView;

		}
	}
}
